import axios from "axios";
import { API_CONFIG } from "../config/api.config";

// 创建 axios 实例
const request = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取 token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data;

    console.log("请求成功:", res);

    // 这里可以根据后端的响应结构定制处理逻辑
    if (res.code === 200) {
      return res;
    }

    // 处理特定错误，比如token过期
    if (res.code === 401) {
      // token过期处理
      localStorage.removeItem("token");
      // window.location.href = "/login";
      return Promise.reject(new Error(res.msg || "Error"));
    }
    return Promise.reject(res);
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

export default request;
